import sys
import os
from PyQt5.QtWidgets import *
from tools.UI_CharacterForm import Ui_Form
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import numpy as np
from bisect import bisect_left

from tools.MtCanvas import Demo

class MeltCharacterForm(QMainWindow, Ui_Form):

    def __init__(self):
        super(MeltCharacterForm, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("熔融行为")
        self.canvas = Demo()
        self.canvas.selectSignal.connect(self.updateData)
        self.navigationToolBar = NavigationToolbar(self.canvas, self)
        self.bar = self.statusBar()
        self.bar.addWidget(self.navigationToolBar)
        self.ax_torque = self.canvas.axes2
        self.ax_temper = self.canvas.axes

        self.gridLayout = QGridLayout(self)
        self.gridLayout.addWidget(self.canvas)
        self.groupBox_curve.setLayout(self.gridLayout)

        self.torqueData = None
        self.temperData = None
        self.timeData = None
        self.btnInit()

        self.radioInit()
        self.test()

    def getCas(self):
        try:
            screen = QApplication.primaryScreen()
            picture = screen.grabWindow(self.winId())
            picture.save("熔融特征.jpg")
        except Exception as e:
            print(e)

    def btnInit(self):
        self.btn_load.clicked.connect(self.loadData)
        self.btn_print.clicked.connect(self.getCas)

    def loadData(self):
        """选择文件夹加载数据"""
        directory = QFileDialog.getExistingDirectory()
        for root, dirs, files in os.walk(directory):
            for file in files:
                if file == "Torque.csv":
                    print("load torque")
                    path = root + "/torque.csv"
                    data = np.loadtxt(path, delimiter=',')
                    self.torqueData = data[0].tolist()
                    self.timeData = data[1].tolist()

                if file == "Melt Temper.csv":
                    print("load Temper")
                    path = root + "/Melt Temper.csv"
                    data = np.loadtxt(path, delimiter=',')
                    self.temperData = data[0].tolist()
            self.canvas.connect()
            self.draw()

    def updateData(self, idx, x):
        i = self.snap(x)
        if i >= len(self.timeData):
            i = len(self.timeData)-1
        x = self.timeData[i]
        torque = str(self.torqueData[i])
        temper = str(self.temperData[i])

        if idx == 0:
            self.lineEdit_torque_A.setText(torque)
            self.lineEdit_Melt_A.setText(temper)
            self.lineEdit_time_A.setText("%.2f" % x)
        elif idx == 1:
            self.lineEdit_torque_B.setText(torque)
            self.lineEdit_Melt_B.setText(temper)
            self.lineEdit_time_B.setText("%.2f" % x)
        elif idx == 2:
            self.lineEdit_torque_X.setText(torque)
            self.lineEdit_Melt_X.setText(temper)
            self.lineEdit_time_X.setText("%.2f" % x)
        elif idx == 3:
            self.lineEdit_torque_G.setText(torque)
            self.lineEdit_Melt_G.setText(temper)
            self.lineEdit_time_G.setText("%.2f" % x)
        elif idx == 4:
            self.lineEdit_torque_E.setText(torque)
            self.lineEdit_Melt_E.setText(temper)
            self.lineEdit_time_E.setText("%.2f" % x)

    def snap(self, x):
        """在dataIime找到最接近x的时间索引"""
        if self.timeData:
            return bisect_left(self.timeData, x)
        else:
            return None

    def draw(self):
        """绘制曲线"""
        # 先刷新画布
        self.radioInit()
        self.canvas.updateAxes()
        self.ax_torque.plot(self.timeData, self.torqueData, 'b', label="扭矩")
        self.ax_temper.plot(self.timeData, self.temperData, 'r', label="温度")
        self.ax_torque.legend(loc=1)
        self.ax_temper.legend(loc=2)
        self.canvas.draw()

    def radioInit(self):
        self.radiobtn_A.setChecked(True)
        self.radiobtn_B.setChecked(True)
        self.radiobtn_X.setChecked(True)
        self.radiobtn_G.setChecked(True)
        self.radiobtn_E.setChecked(True)

    def test(self):
        self.radiobtn_A.toggled.connect(lambda :self.showAndHide(0))
        self.radiobtn_B.toggled.connect(lambda :self.showAndHide(1))
        self.radiobtn_X.toggled.connect(lambda :self.showAndHide(2))
        self.radiobtn_G.toggled.connect(lambda :self.showAndHide(3))
        self.radiobtn_E.toggled.connect(lambda :self.showAndHide(4))

    def showAndHide(self, idx):
        try:
            print(idx)
            if idx == 0:
                if not self.radiobtn_A.isChecked():
                    self.canvas.vline_a.remove()
                    # self.canvas.vlines[idx] = None

                else:
                    self.canvas.axes.add_line(self.canvas.vline_a)
                    # self.canvas.vlines[idx] = self.canvas.vline_a
            elif idx == 1:
                if not self.radiobtn_B.isChecked():
                    self.canvas.vline_b.remove()
                    # self.canvas.vlines[idx] = None
                else:
                    self.canvas.axes.add_line(self.canvas.vline_b)
                    # self.canvas.vlines[idx] = self.canvas.vline_b
            elif idx == 2:
                if not self.radiobtn_X.isChecked():
                    self.canvas.vline_x.remove()
                    # self.canvas.vlines[idx] = None
                else:
                    self.canvas.axes.add_line(self.canvas.vline_x)
                    # self.canvas.vlines[idx] = self.canvas.vline_x
            elif idx == 3:
                if not self.radiobtn_G.isChecked():
                    self.canvas.vline_g.remove()
                    # self.canvas.vlines[idx] = None
                else:
                    self.canvas.axes.add_line(self.canvas.vline_g)
                    # self.canvas.vlines[idx] = self.canvas.vline_g
            elif idx == 4:

                if not self.radiobtn_E.isChecked():
                    self.canvas.vline_e.remove()
                    # self.canvas.vlines[idx] = None
                else:
                    self.canvas.axes.add_line(self.canvas.vline_e)
                    # self.canvas.vlines[idx] = self.canvas.vline_e
                    print("yes")
        except Exception as e:
            print(e)
        self.canvas.draw()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = MeltCharacterForm()
    demo.show()
    app.exec_()



